package dmwr.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dmwr.Dmwr;
import dmwr.filter.Secure;
import dmwr.service.Service;
import dmwr.web.Http;

public class Play extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final long SESSION_LENGTH = 25;

	private Controller c = new Controller();

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (Http.request().getParameter("poolId") == null) {
			c.start();
		} else {
			String method = Http.request().getMethod();
			if ("GET".equals(method)) {
				c.show();
			} else if ("POST".equals(method)) {
				c.submit();
			}
		}
	}

	class Controller {

		void start() {
			Http.request().setAttribute("pools",
					Dmwr.service().listPools(1, 100).getItems());
			Http.forward("/play/start.jsp");
		}

		void show() {
			long poolId = Long.parseLong(Http.request().getParameter("poolId"));
			Http.request().setAttribute(
					"session",
					Dmwr.service().getSession(
							Secure.context().getUser().getUsername(), poolId,
							SESSION_LENGTH));
			// StringBuilder sb = new StringBuilder();
			// for (char c : entry.getText2().toCharArray()) {
			// sb.append(Character.isAlphabetic(c) ? '*' : c);
			// }
			// request.setAttribute("text2", sb.toString());
			Http.forward("/play/shot.jsp");
		}

		void submit() {
			long poolId = Long.parseLong(Http.request().getParameter("poolId"));
			String[] f = Http.indexedParameter("feedback");
			List<Service.Answer> answers = new ArrayList<Service.Answer>();
			for (int i = 0; i < f.length; i++) {
				int p1 = f[i].indexOf('_');
				int p2 = f[i].indexOf('_', p1 + 1);
				long instant = Long.parseLong(f[i].substring(0, p1));
				long entryId = Long.parseLong(f[i].substring(p1 + 1, p2));
				boolean ok = "ok".equals(f[i].substring(p2 + 1));
				answers.add(new Service.Answer(instant, entryId, ok));
			}
			Dmwr.service().saveSession(
					Secure.context().getUser().getUsername(), poolId, answers);
			Http.redirect("/play?poolId=" + poolId);
		}
	}
}
